//
//  WYUserAccaseViewModel.swift
//  weibo
//
//  Created by 王玉东 on 16/4/10.
//  Copyright © 2016年 wyd. All rights reserved.
//

import UIKit
private var userInfoKey = "com.wangyu.userifonKey"

class WYUserAccaseViewModel: NSObject {
    
    

    static let sharedViewModel:WYUserAccaseViewModel = WYUserAccaseViewModel()
    
    var userAccout:WYUserAccase?
    
    override init() {
        super.init()
        
        userAccout = self.loadUserInfo()
        
    }
    
    
    var login: Bool {
        
 //如果token不为空,用户token不过期
if let u = userAccout  where u.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
        
            return true
        }
        userAccout = nil
        return false
    }
    
  
func loadAccessToken(code:String,finished: (isSuccess: Bool) -> ()) {
        
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        
//        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type": "authorization_code","code":code,"redirect_uri":redirect_uri]
        
        HMNetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
        
          if error != nil {
            print(error)
                finished(isSuccess: false)
                        return
                }
            self.loadUser(result!,finished: finished)
        }
        
//        HMNetworkTools.sharedTools.request(HMHttpMethods.POST, urlString: urlString, parameters: parameters) { (result, error) -> () in
//        
//            if error != nil {
//            print(error)
//            finished(isSuccess: false)
//                return
//            }
//            self.loadUser(result!,finished: finished)
//        }
    }
    
    var herdUrl:NSURL? {
        
        let url = NSURL(string: userAccout?.avatar_large ?? "")
        
        return url
        
    }
    
    
//获取用户信息
 private  func loadUser(result:AnyObject,finished: (isSuccess: Bool) -> ()){
        
        guard let dic = result as?[String:AnyObject] else{
            finished(isSuccess: false)
            print("数据错误")
            return
        }
        let token = dic["access_token"]!
        let uid = dic["uid"]!
//        let  urlstring = "https://api.weibo.com/2/users/show.json"
//        let parameters = ["access_token": token, "uid": uid]
    
    HMNetworkTools.sharedTools.loadUserInfo(token, uid: uid) { (result, error) -> () in
        
        if error != nil {
            finished(isSuccess: false)
            print("信息错误")
            return
            
        }
        
        //         print(result)
        
        //合并用户信息
        guard var userInfo = result as? [String: AnyObject] else {
            finished(isSuccess: false)
            return
        }
        
        for (k , v) in dic {
            userInfo[k] = v
        }
        //字典转模型(去掉没有值的数据)
        
        self.saveUserAccount(userInfo)
        finished(isSuccess: true)
    }
  

    }
    
//        HMNetworkTools.sharedTools.request(HMHttpMethods.GET, urlString: urlstring, parameters: parameters) { (result, error) -> () in
//            
//            if error != nil {
//                finished(isSuccess: false)
//                print("信息错误")
//                return
//                
//            }
//            
//            //         print(result)
//            
//            //合并用户信息
//            guard var userInfo = result as? [String: AnyObject] else {
//                finished(isSuccess: false)
//                return
//            }
//            
//            for (k , v) in dic {
//                userInfo[k] = v
//            }
//            //字典转模型(去掉没有值的数据)
//            
//            self.saveUserAccount(userInfo)
//            finished(isSuccess: true)
//        }
//    
//    }
}

//MARK:数据的保存和读取
extension WYUserAccaseViewModel {
    

    func saveUserAccount(userInfo: [String : AnyObject]) {
    
        let accout = WYUserAccase(dic: userInfo)
        
        //将数据放到内存一份
        self.userAccout = accout
        let keys = ["access_token","avatar_large","name","expires_in","uid","expires_date"]
        //获取数组
        let dict = accout.dictionaryWithValuesForKeys(keys)
        
        print(dict)
        let userDafult = NSUserDefaults.standardUserDefaults()
        
        userDafult.setObject(dict, forKey: userInfoKey)
        //同步
        userDafult.synchronize()

    }
    //MARK:读取数据
    func loadUserInfo() -> WYUserAccase? {
        //1.获取字典信息
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey) as? [String : AnyObject] else {
            return nil
        }

//        //2.将字典转换为模型
        let account = WYUserAccase(dic: dict)
        print(account)
        return account
    }
    
 


}
